package com.yuan.util.object;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author YouYuan
 * @version 1.0
 * @CreateDate 2018/5/10 16:40
 * @UpdateDate 2018/5/10 16:40
 */
public class ObjectConver {

    public static String dateFormat = "yyyy-MM-dd HH:mm:ss";
    public static SerializeConfig serializeConfig = new SerializeConfig();

    static {
        serializeConfig.put(java.util.Date.class, new SimpleDateFormatSerializer(dateFormat));
        serializeConfig.put(java.sql.Timestamp.class, new SimpleDateFormatSerializer(dateFormat));
        serializeConfig.put(java.sql.Date.class, new SimpleDateFormatSerializer(dateFormat));
    }

    public static List<Map> toListMap(List listBean) {
        List<Map> list = new ArrayList<Map>();
        if (listBean != null && listBean.size() > 0) {
            String jsonArrayStr = JSONArray.toJSONString(listBean, serializeConfig);
            list = ((List<Map>) JSONArray.parseObject(jsonArrayStr, List.class));
        }
        return list;
    }

    public static Map beanToMap(Object dto) {
        Map map = new HashMap();
        if (dto != null) {
            String text = JSON.toJSONString(dto, serializeConfig, SerializerFeature.WriteMapNullValue);
            map = JSON.parseObject(text, Map.class);
        }
        return map;
    }

    public static <T> T mapToBean(Map map, Class<T> cls) {
        if (map != null) {
            String text = JSON.toJSONString(map, serializeConfig);
            return JSON.parseObject(text, cls);
        }
        return null;
    }

    /**
     * MapList转换为BeanList
     * @param listMap
     * @param cls
     * @param <T>
     * @return
     */
    public static<T> List<T> toBeanList(List<Map> listMap, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        if (listMap != null) {
            for (Map m : listMap) {
                list.add(mapToBean(m, cls));
            }
        }
        return list;
    }
}
